package com.controller;

import com.pojo.Userdetailed;
import com.pojo.Userinfo;
import com.service.UserManagerService;
import com.util.Controller;
import com.util.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
public class UserManagerController {
    //默认页面
    @RequestMapping("/home")
    public String home(HttpServletRequest request, HttpServletResponse response){
        return  "index";
    }
    //登录页面
    @RequestMapping("/userLogin")
    public String userLogin(HttpServletRequest request, HttpServletResponse response){
        String account = request.getParameter("account");
        String password = request.getParameter("password");

        UserManagerService um=new UserManagerService();
        Userinfo userinfo = um.userLogin(account, password);
        if(userinfo!=null){
            request.getSession().setAttribute("currentUser", userinfo);
        }else{
            request.setAttribute("msg", "账号或密码错误");
        }
        return "index";
    }
    //退出页面
    @RequestMapping("/userExit")
    public String userExit(HttpServletRequest request, HttpServletResponse response){
        request.getSession().invalidate();
        return "index";
    }
    //注册页面
    @RequestMapping("/userReg")
    public String userReg(HttpServletRequest request, HttpServletResponse response){
        String account = request.getParameter("account");
        String password = request.getParameter("password");

        UserManagerService um=new UserManagerService();
        Userinfo userinfo = new Userinfo();
        userinfo.setAccount(account);
        userinfo.setPassword(password);
        int num = um.userReg(userinfo);
        if(num==1){
            request.setAttribute("msg", "注册成功");
        }else if(num==0){
            request.setAttribute("msg", "账号已存在");
        }else{
            request.setAttribute("msg", "注册失败");
        }
        return "index";
    }

    /**
     * ajax用户是否存在的校验
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/accountCheck")
    public String accountCheck(HttpServletRequest request, HttpServletResponse response){
        String account = request.getParameter("account");
        UserManagerService um=new UserManagerService();
        Userinfo userinfo = um.queryUserByAccount(account);
        String result="";
        if(userinfo!=null){
            result = "false";
        }else{
            result = "true";
        }
        return "ajax:"+result;
    }

    /**
     * ajax查询用户方法
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/queryUser")
    public List<Userinfo> queryUser(HttpServletRequest request, HttpServletResponse response){
        String account = request.getParameter("account");
        String sex = request.getParameter("sex");

        Userinfo userinfo = new Userinfo();
        userinfo.setAccount(account);
        Userdetailed ud=new Userdetailed();
        ud.setSex(sex);
        userinfo.setUd(ud);

        UserManagerService um=new UserManagerService();
        List<Userinfo> userinfoList = um.queryUserInfoList(userinfo);
        System.out.println(userinfoList);
        return userinfoList;
    }

        //用户信息页面
    @RequestMapping("/userUpdatePage")
    public String userUpdatePage(HttpServletRequest request, HttpServletResponse response){
        Userinfo currentUser = (Userinfo)request.getSession().getAttribute("currentUser");
        UserManagerService um=new UserManagerService();
        Userinfo userinfo = um.queryUserInfo(currentUser.getId());
        request.setAttribute("user",userinfo);

        return "userinfoUpdate";
    }
    
    //用户信息修改页面
    @RequestMapping("/userUpload")
    public String userUpload(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        request.setCharacterEncoding("utf-8");
        Userinfo currentUser = (Userinfo) request.getSession().getAttribute("currentUser");
        Userdetailed userdetailed = new Userdetailed();
        currentUser.setUd(userdetailed);

        userdetailed.setName(request.getParameter("name"));
        userdetailed.setSex(request.getParameter("sex"));
        userdetailed.setBirthdayStr(request.getParameter("birthday"));
        userdetailed.setAddress(request.getParameter("address"));
        userdetailed.setEmail(request.getParameter("email"));
        userdetailed.setPhone(request.getParameter("phone"));
        userdetailed.setHeadPicUrl(request.getParameter("headPicUrl"));

        String checkcode = request.getParameter("checkcode");
        String checkCode = request.getSession().getAttribute("checkCode").toString();
        request.getSession().removeAttribute("checkCode");
        //验证码检查
        if (!checkcode.equalsIgnoreCase(checkCode)) {
            request.setAttribute("msg", "验证码错误");
            request.setAttribute("user", currentUser);
            return "userinfoUpdate";
        }
        userdetailed.setUserid(currentUser.getId());

        String savePath = saveFile(request,"uploadFile");
        if (savePath != null) {
            //设置上传文件的路径
            userdetailed.setHeadPicUrl(savePath);
        }
        UserManagerService um = new UserManagerService();
        if (um.updateUserdetailed(userdetailed)) {
            request.setAttribute("msg", "修改成功！");
        } else {
            request.setAttribute("msg", "修改失败！");
        }

        request.setAttribute("user", currentUser);
        return "userinfoUpdate";
    }
    //axios查询所有用户
    @RequestMapping("/queryAllUser")
    public List<Userinfo> queryAllUser(HttpServletRequest request, HttpServletResponse response){
        String account = request.getParameter("account");
        String name = request.getParameter("name");

        Userinfo userinfo = new Userinfo();
        userinfo.setAccount(account);
        Userdetailed userdetailed = new Userdetailed();
        userdetailed.setName(name);
        userinfo.setUd(userdetailed);

        UserManagerService um = new UserManagerService();
        List<Userinfo> userList = um.queryAllUser(userinfo);

        return userList;
    }

    /**
     * 图片上传方法
     * @param request
     * @param response
     * @return
     * @throws IOException
     * @throws ServletException
     */
    @RequestMapping("/imgUpload")
    public String imgUpload(HttpServletRequest request, HttpServletResponse
            response) throws IOException, ServletException {
        //设置图⽚保存路径
        String savePath = "upload/";
        String fullPath = request.getServletContext().getRealPath("/" + savePath);
        File file = new File(fullPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        //获取上传的⽂件对象
        Part part = request.getPart("file");
        //获取头信息
        String header = part.getHeader("Content-Disposition");
        //截取⽂件后缀名
        String suffix = header.substring(header.lastIndexOf(".")).replace("\"", "");
        //构建⽂件名
        String fileName = UUID.randomUUID().toString().replace("-", "") + suffix;
        //保存⽂件
        if (fileName != null && !"".equals(fileName)) {
            try {
                part.write(fullPath + fileName);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //返回图⽚相对路径
        return "ajax:"+savePath + fileName;
    }
        //存储文件
    private String saveFile(HttpServletRequest request,String name) throws IOException, ServletException {
        Part uploadFile = request.getPart(name);
        if (uploadFile.getContentType() != null) {
            String savePath = request.getServletContext().getRealPath("upload");
            Date date = new Date();
            savePath += "/" + date.getYear();
            savePath += "/" + (date.getMonth() + 1);
            savePath += "/" + date.getDate();

            System.out.println("savePath: " + savePath);
            File file = new File(savePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            //从元素中获取文件名
            String header = uploadFile.getHeader("Content-Disposition");
            //获取文件名
            String fileName = header.substring(header.lastIndexOf("=")+1).replace("\"", "");
            if(fileName.equals("")) {
                return null;
            }
            //截取文件后缀名
            String suffix = header.substring(header.lastIndexOf(".")).replace("\"", "");
//                System.out.println(fileName);
            //构建新文件名
            fileName = UUID.randomUUID().toString().replace("-", "") + suffix;
            System.out.println(fileName);

            //保存文件
            if (fileName != null && !"".equals(fileName)) {
                try {
                    uploadFile.write(savePath + "/" + fileName);
                    return savePath.substring(savePath.indexOf("upload")) + "/" + fileName;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}
